package com.glodon.paas.sdk;

import oauth.signpost.signature.QueryStringSigningStrategy;

import com.glodon.paas.sdk.account.Account;
import com.glodon.paas.sdk.document.Document;
import com.glodon.paas.security.oauth1.OAuthConsumerEx;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;

public class PaasClient {
	
	private final OAuthConsumerEx consumer;
	private EndpointConfig endpoints;
	private ClientConfig clientConfig; 
	
	/**
	 * @param consumerKey
	 * @param consumerSecret
	 * @param host
	 */
	public PaasClient(String consumerKey, String consumerSecret, String host) {
		this(consumerKey, consumerSecret, new EndpointConfig(host));
		clientConfig = new DefaultClientConfig();
		clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
	}
	
	/**
	 * @param consumerKey
	 * @param consumerSecret
	 * @param endpoints
	 */
	public PaasClient(String consumerKey, String consumerSecret, EndpointConfig endpoints) {
		consumer = new OAuthConsumerEx(consumerKey, consumerSecret);
		consumer.setSigningStrategy(new QueryStringSigningStrategy());
		this.endpoints = endpoints;
	}
	
	/**
	 * @return
	 */
	public EndpointConfig getEndpointConfig() {
		return endpoints;
	}
	
	/**
	 * @param endpoints
	 */
	public void setEndpointConfig(EndpointConfig endpoints) {
		this.endpoints = endpoints;
	}
	
	/**
	 * @param token
	 * @param tokenSecret
	 */
	public void setTokenWithSecret(String token, String tokenSecret) {
		consumer.setTokenWithSecret(token, tokenSecret);
	}
	
	/**
	 * @param url
	 * @param method
	 * @return
	 * @throws SdkException
	 */
	public String signUrl(String url, String method) throws SdkException {
		try {
			return consumer.sign(url, method);
		} catch (Exception e) {
			throw new SdkException("Failed to sign url: " + method + " " + url, e);
		} 
	}
	
	/**
	 * @param url
	 * @param method
	 * @return
	 * @throws SdkException
	 */
	public WebResource signAndCreateResource(String url, String method) throws SdkException {
		try {
			String signedUrl = consumer.sign(url, method);
			return Client.create(clientConfig).resource(signedUrl);
		} catch (Exception e) {
			throw new SdkException("Failed to sign url: " + method + " " + url, e);
		} 
	}
	
	public Account account() {
		return new Account(this);
	}
	
	public Document document() {
		return new Document(this);
	}
	

}
